//
//  GameCenterHelper.m
//  TowerDefence
//
//  Created by K3 on 6/11/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "GameCenterHelper.h"
#import "iCoreGUIController.h"

@implementation GameCenterHelper;

@synthesize gameCenterAvailable;

static GameCenterHelper *shareHelper = nil;

+(GameCenterHelper *)shareInstance:(iCoreGUIController *)_mainGUIControler; {
    if(!shareHelper) {
        shareHelper = [[GameCenterHelper alloc]initGameCenterHelperWith:_mainGUIControler];
    }
    
    return shareHelper;
}

-(BOOL)isGameCenterAvailable {
    //check GKLocalPlayer API
    Class gameCenterClass = NSClassFromString(@"GKLocalPlayer");
    
    //check version iOS of devide 4.1 or later
    NSString *reqVersion = @"4.1";
    NSString *curVersion = [[UIDevice currentDevice] systemVersion];
    
    BOOL osVersionIsSupported = [curVersion compare:reqVersion options:NSNumericSearch] != NSOrderedAscending;
    
    return gameCenterClass && osVersionIsSupported;
}

-(id)initGameCenterHelperWith:(iCoreGUIController *)_mainGUIController {
    self = [super init];
    
    mainGUIController = _mainGUIController;
    gameCenterAvailable = [self isGameCenterAvailable];
    if(gameCenterAvailable) {
        NSNotificationCenter *nortify = [NSNotificationCenter defaultCenter];
        [nortify addObserver:self selector:@selector(authenticationChange) name:GKPlayerAuthenticationDidChangeNotificationName object:nil];
    }
    
    return self;
}
         
-(void)authenticationChange {
    if([GKLocalPlayer localPlayer].isAuthenticated && !userAuthenticate) {
        NSLog(@"Authentication changed: player authenticated.");
        userAuthenticate = TRUE;           
    } else if (![GKLocalPlayer localPlayer].isAuthenticated && userAuthenticate) {
        NSLog(@"Authentication changed: player not authenticated");
        userAuthenticate = FALSE;
    }
}

-(void)authenticateLocalUser {
    if(!gameCenterAvailable) {
        return;
    }
    
    NSLog(@"Authenticating local user...");
    if ([GKLocalPlayer localPlayer].authenticated == NO) {     
        [[GKLocalPlayer localPlayer] authenticateWithCompletionHandler:nil];        
    } else {
        NSLog(@"Already authenticated!");
    }
}

@end
